#include <stdio.h>
#include <stdlib.h>
#include <alsa/asoundlib.h>

#define PCM_DEVICE "default"

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s <wav file>\n", argv[0]);
        return 1;
    }

    FILE *wav_file = fopen(argv[1], "rb");
    if (!wav_file) {
        perror("Failed to open file");
        return 1;
    }

    // 读取WAV文件头
    char header[44];
    fread(header, 1, 44, wav_file);

    // 检查WAV文件格式
    if (header[0] != 'R' || header[1] != 'I' || header[2] != 'F' || header[3] != 'F' ||
        header[8] != 'W' || header[9] != 'A' || header[10] != 'V' || header[11] != 'E') {
        fprintf(stderr, "Not a valid WAV file\n");
        fclose(wav_file);
        return 1;
    }

    // 获取音频参数
    int channels = *(short *)(header + 22);
    int sample_rate = *(int *)(header + 24);
    int bits_per_sample = *(short *)(header + 34);

    // 打开PCM设备
    snd_pcm_t *pcm_handle;
    snd_pcm_open(&pcm_handle, PCM_DEVICE, SND_PCM_STREAM_PLAYBACK, 0);

    // 设置PCM参数
    snd_pcm_hw_params_t *params;
    snd_pcm_hw_params_alloca(&params);
    snd_pcm_hw_params_any(pcm_handle, params);
    snd_pcm_hw_params_set_access(pcm_handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
    snd_pcm_hw_params_set_format(pcm_handle, params, bits_per_sample == 16 ? SND_PCM_FORMAT_S16_LE : SND_PCM_FORMAT_U8);
    snd_pcm_hw_params_set_channels(pcm_handle, params, channels);
    snd_pcm_hw_params_set_rate_near(pcm_handle, params, &sample_rate, 0);
    snd_pcm_hw_params(pcm_handle, params);

    // 播放音频数据
    char buffer[1024];
    while (1) {
        int read = fread(buffer, 1, sizeof(buffer), wav_file);
        if (read == 0)
            break;

        int frames = read / (channels * (bits_per_sample / 8));
        snd_pcm_writei(pcm_handle, buffer, frames);
    }

    // 关闭PCM设备
    snd_pcm_drain(pcm_handle);
    snd_pcm_close(pcm_handle);

    // 关闭文件
    fclose(wav_file);

    return 0;
}